/**
 * @Title: dropdown_directive.js
 * @Description: 下拉
 * Copyright: Copyright (c) 2014 
 * Company:中国平安
 *
 * @Project HIMS-FWA
 * @author QIANDUO875
 * @date 2014年9月23日 下午2:36:33
 * @version V1.0
 */
;
(function(){
	'use strict';
	
	var app = angular.module('fwa.directives');
	app.directive('fwaDropdown', ['$compile','$parse', function($compile,$parse){
		
		var tmpl = '\
					<button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown">\
						{{selectedItem.#labelField# || selectedItem}} <span class="caret"></span>\
				  	</button>\
				  	<ul class="dropdown-menu" role="menu">\
					    <li ng-repeat="item in items" ng-class="{\'active\':item == selectedItem}">\
							<a ng-bind="item.#labelField# || item" ng-click="onClickItem(item)"></a>\
						</li>\
				  	</ul>';
		
		function link($scope, $elm , $attrs, $ctrls) {
			var labelFiledName = $attrs.labelField || 'label',
				valueFieldName = $attrs.valueField,
				valueGetFn = $parse($attrs.value),
				valueSetFn = valueGetFn.assign;
			
			$elm.append($compile(tmpl.replace(/#labelField#/g, labelFiledName))($scope));
			
			function selectedChange(item) {
				if($scope.selectedItem == item) {
					return;
				}
				var value;
				if(valueFieldName) {
					value = item?$scope.selectedItem[valueFieldName]:null;
				} else {
					value = item;
				}
				valueSetFn($scope.$parent, value);
			}
			
			function valueOrImtemsChange(items, v) {
				$scope.selectedItem = null;
				$.each(items, function(i, d){
					if(valueFieldName && d[valueFieldName] === v) {
						$scope.selectedItem = d;
					} 
					else if(!valueFieldName && d === v) {
						$scope.selectedItem = d;
					}else if(d == v){
						$scope.selectedItem = d;
					}
				});
			}
			
			//监听data
			$scope.$parent.$watchCollection($attrs.data, function(v){
				$scope.items = v;
				
				if(v) {
					valueOrImtemsChange(v,valueGetFn($scope.$parent));
				}
			});
			
			//选择事件
			$scope.onClickItem = function(item) {
				selectedChange(item);
			}
			
			//监听value, 改变selectedItem
			$scope.$parent.$watch($attrs.value, function(v){
				valueOrImtemsChange($scope.items, v);
			});
		}
		
		return {
			restrict:'E',
			replace:true,
			template:'<div class="btn-group"></div>',
			scope:true,
			link:link
		};
		
	}]);
	
})();